package com.ruoyi.mqtt.controller;

import com.alibaba.fastjson2.JSON;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.mqtt.config.HbaseTableTemplate;
import com.ruoyi.mqtt.config.HbaseTemplate;
import com.ruoyi.mqtt.config.MqttClientConnect;
import com.ruoyi.mqtt.pojo.Mqtt;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/mqtt")
public class PublishController extends BaseController {

    @Autowired
    MqttClientConnect mqttClientConnect;

    @Autowired
    private HbaseTemplate hbaseTemplate;

    @Autowired
    private HbaseTableTemplate hbaseTableTemplate;


    // 发送自定义消息内容，且指定主题
    @GetMapping("/mqtt")
    public void publish(Mqtt mqtt) throws MqttException {
        mqtt.setTime(LocalDateTime.now());
        mqttClientConnect.publish(mqtt.getTopic(), JSON.toJSONString(mqtt));
    }

    @GetMapping("createTable1")
    public void createTable1(){
        List<String> list = new ArrayList<>();
        list.add("info");
        boolean temperatureRecording = hbaseTableTemplate.createTable("MqttLogs", list);
        System.out.println(temperatureRecording);
    }

    /**
     * HBase查询列表
     * @author songshijia
     * @date 2023/11/28
     * @return java.util.List<com.mqtt.pojo.TemperatureRecording>
     */
    @GetMapping("list")
    public TableDataInfo list(){
        Map<String, Map<String, String>> temperatureRecording = hbaseTemplate.getResultScanner("MqttLogs");

        List<Mqtt> list = new ArrayList<>();
        Set<String> set = temperatureRecording.keySet();//1001  1002

        set.forEach(keyrow->{
            Map<String, String> stringStringMap = temperatureRecording.get(keyrow);

            for (String s : stringStringMap.keySet()) {

            }

//            JSON.parseObject(stringStringMap,Mqtt.class);
            Mqtt mqtt = new Mqtt();
            mqtt.setVin(stringStringMap.get("vin"));
            mqtt.setTemperature(Double.valueOf(stringStringMap.get("temperature")));
            mqtt.setHumidity(Double.valueOf(stringStringMap.get("humidity")));
            mqtt.setTopic(stringStringMap.get("topic"));
            mqtt.setMaxTemperature(Double.valueOf(stringStringMap.get("maxTemperature")));
            mqtt.setMinTemperature(Double.valueOf(stringStringMap.get("minTemperature")));
            mqtt.setMaxHumidity(Double.valueOf(stringStringMap.get("maxHumidity")));
            mqtt.setMinHumidity(Double.valueOf(stringStringMap.get("minHumidity")));
            mqtt.setTime(LocalDateTime.parse(stringStringMap.get("time")));
            list.add(mqtt);
        });

        return getDataTable(list);
    }

}
